package cn.edu.lingnan.lsqn.util;

import java.io.File;

import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;

import cn.edu.lingnan.lsqn.model.LsqnException;

/**
 * 没有集成进系统，后面会考虑
 * @author cdh
 *
 */
public class Word2PDFUtil {
	private static OfficeManager officeManager;
	private static String OFFICE_HOME = "D:\\application\\openoffice\\app";
	private static int port[] = { 8100 };

	public void convert2PDF(String inputFile, String pdfFile) {
		if (inputFile.endsWith(".doc") || inputFile.endsWith(".docx") || inputFile.endsWith(".txt")) {
			File docFile = new File(inputFile);
			System.out.println(docFile.getAbsolutePath());
			if (!docFile.exists())
				throw new LsqnException("文件不存在");
			else {
				startService();
				OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
				converter.convert(new File(inputFile), new File(pdfFile));
				stopService();
			}
		}
	}

	private static void startService() {
		DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
		try {
			configuration.setOfficeHome(OFFICE_HOME);
			configuration.setPortNumbers(port);
			configuration.setTaskExecutionTimeout(1000 * 60 * 5L);
			configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);
			officeManager = configuration.buildOfficeManager();
			officeManager.start(); 
		} catch (Exception ce) {
			throw new  LsqnException(ce);
		}
	}

	private static void stopService() {
		if (officeManager != null) {
			officeManager.stop();
		}
	}
}
